<template>
  <el-card>
    <div slot="header">
      <h3>线索转潜在商品-审核详情</h3>
    </div>
    <div v-loading="pageLoading">
      <BtnRender :render="renderBtnsBar" />
      <el-row>
        <skus-table
          :showSelectCol="isToReview"
          :tableHeight="480"
          :dataSource="TableInfo.list"
          :columns="TableInfo.columns"
          :loading="TableInfo.loading"
          :selectionChange="TableInfo.setSelection"
        >
          <template v-slot:specAttrs="slotProps">
            <AttributePerfectPopover
              showTotal
              prefix="属性值："
              placement="left"
              :complete-status="slotProps.data.row.specAttrStatus"
              :attribute-vos="slotProps.data.row.specAttributeVos"
            />
          </template>
          <template v-slot:basicAttrs="slotProps">
            <AttributePerfectPopover
              showTotal
              prefix="基本信息值："
              placement="right"
              :complete-status="slotProps.data.row.notSpecAttrStatus"
              :attribute-vos="slotProps.data.row.notSpecAttributeVos"
            />
          </template>
          <template v-slot:imageStatusStr="slotProps">
            <PerfectLink
              :complete-status="slotProps.data.row.imageStatus"
              @click="handlePerfectImage(slotProps.data.index, slotProps.data.row)"
            />
          </template>
        </skus-table>
      </el-row>
      <FooterFields :fieldsItems="fieldsItems" :fieldsData="fieldsData" />
    </div>
    <RejectDialog
      :visible.sync="rejectDialog.visible"
      @get-reason="updateRejectReason"
    />
    <SelectProductDialog
      :visible.sync="selectProduct.visible"
      :enumTempProductList="selectProduct.enumTempProductList"
      :validate-select="validateSelectProduct"
      @getSelectResults="updateReplaceProduct"
    />
    <!-- 关联四级类弹框 -->
    <AssociatedDialog
      dialogTitle="关联四级类"
      currentType="1"
      :visible.sync="selectCategory.visible"
      @getSelectResults="updateSelectCategory"
    />
    <!-- 图文完善弹框 -->
    <SaveLatentImageDialog
      :visible.sync="perfectImage.visible"
      :image-info="perfectImage.imageInfo"
      :record-detail-uuid="perfectImage.recordDetailUuid"
      @success="updateRecordDetails"
    />
  </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import RejectDialog from './components/RejectDialog';
import AssociatedDialog from '../components/AssociatedDialog';
import SelectProductDialog from '@/pages/commodity/components/SelectProductDialog';
import PerfectLink from '../components/PerfectLink';
import AttributePerfectPopover from '../components/AttributePerfectPopover';
import SaveLatentImageDialog from '../latentProduct/components/SaveLatentImageDialog';
import FooterFields from '@/pages/commodity/components/FooterFields/DataRender';
import { TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import { PRODUCT_TYPES_ENUMS } from '@/constants/commodity';
import skusPage from '@/mixins/commodity/skusPage';
import { TABLE_COLUMNS, getRenderRejectNoteCol, FOOTER_FIELDS } from './constants/recordView';
import {
  REJECT_REASON_ENUMS,
  REVIEW_STATUS_ENUMS,
  WORKFLOW_STATUS_ENUMS
} from './constants/config';
import { COMMON_COMP_CONFIGS } from '../latentProduct/constants/common';
import {
  getTempToPotentialInfoService,
  saveAuditDetailService,
  exportAttr4RecordDetailService,
  getByRecordNoService
} from '@/api/commodity/temporaryPurchasingGoods/latentProductRecord';
export default {
  mixins: [skusPage],
  components: {
    SkusTable,
    BtnRender,
    RejectDialog,
    AssociatedDialog,
    SelectProductDialog,
    PerfectLink,
    AttributePerfectPopover,
    SaveLatentImageDialog,
    FooterFields
  },
  data () {
    return {
      pageLoading: false,
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      fieldsData: {},
      fieldsItems: FOOTER_FIELDS,
      btnLoading: {
        export: false,
        submit: false
      },
      rejectDialog: {
        visible: false
      },
      selectProduct: {
        ...COMMON_COMP_CONFIGS,
        enumTempProductList: [PRODUCT_TYPES_ENUMS.NORMAL, PRODUCT_TYPES_ENUMS.POTENTIAL]
      },
      selectCategory: {
        ...COMMON_COMP_CONFIGS
      },
      perfectImage: {
        ...COMMON_COMP_CONFIGS,
        imageInfo: null,
        recordDetailUuid: ''
      }
    }
  },
  created () {
    this.setTableColumns()
    this.updateRecordDetails()
    this.updateRecordFiledsInfo()
  },
  mounted () {
    window.addEventListener('beforeunload', this.handleBeforeUnload)
  },
  beforeDestroy () {
    window.removeEventListener('beforeunload', this.handleBeforeUnload)
  },
  computed: {
    isToReview () {
      const isFlag = this.fieldsData?.workflowStatus == WORKFLOW_STATUS_ENUMS.ToReview
      return isFlag
    }
  },
  methods: {
    handleBeforeUnload (event) {
      if (!this.isToReview) return
      event.preventDefault()
      event.returnValue = ''
    },
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const hasAuth = this.$route?.query?.hasAuth ?? false
      const btnList = [
        {
          label: '导出属性',
          method: this.handleExportAttrs,
          loading: this.btnLoading.export,
          hasAuth,
          authLabel: '导出'
        },
        {
          label: '批量驳回',
          method: this.handleBatchReject,
          disabled: this.TableInfo.isNullSelection(),
          hasAuth,
          authLabel: '详情页审核'
        },
        {
          label: '批量通过',
          method: this.handleBatchPass,
          disabled: this.TableInfo.isNullSelection(),
          hasAuth,
          authLabel: '详情页审核'
        },
        {
          label: '提交',
          method: this.handleSubmit,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.submit,
          hasAuth,
          authLabel: '详情页提交'
        }
      ]
      const finalBtns = this.isToReview ? btnList : []
      return getListPageBtnsBar(h, finalBtns, this.showBtn)
    },
    // 设置表格表列
    setTableColumns () {
      const columns = TABLE_COLUMNS.map(item => {
        if (item.key == 'reasonNote') return getRenderRejectNoteCol(this.handleOpenDialogSelect)
        return item
      })
      this.TableInfo.setColumns(columns)
    },
    // 导出属性
    async handleExportAttrs () {
      const data = this.TableInfo.list
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportAttr4RecordDetailService(data, loadingFn)
      createExcelByExport({ excelTitle: `线索转潜在商品审核详情导出属性_${generateUuid()}`, res })
    },
    // 批量驳回
    handleBatchReject () {
      this.rejectDialog.visible = true
    },
    // 批量通过
    handleBatchPass () {
      const hasReject = this.TableInfo.selection.some(
        item => item.auditState == REVIEW_STATUS_ENUMS.Reject && (item.reasonType || item.reasonNote)
      )
      // 提示执行回调
      const confirmExecute = () => {
        this.$confirm('勾选项有审核驳回，会清空驳回原因和备注，确定要进行审核通过吗？', '提示', {
          type: 'warning',
        }).then(() => {
          this.batchUpdateAuditInfo(REVIEW_STATUS_ENUMS.Pass)
        }).catch(() => {})
      }
      hasReject ? confirmExecute() : this.batchUpdateAuditInfo(REVIEW_STATUS_ENUMS.Pass)
    },
    // 提交
    handleSubmit () {
      if (this.validateSubmit()) return
      this.submitRecordDetails()
    },
    // 打开弹框选择
    handleOpenDialogSelect (row, index) {
      if (row.reasonType == REJECT_REASON_ENUMS.Product) return this.selectProduct.open(index)
      if (row.reasonType == REJECT_REASON_ENUMS.CategoryAndClassify) return this.selectCategory.open(index)
    },
    // 完善图文信息
    handlePerfectImage (index, row) {
      this.perfectImage.imageInfo = row.tempSkuImageVo
      this.perfectImage.recordDetailUuid = row.recordDetailUuid
      this.perfectImage.open(index)
    },
    // 更新驳回原因
    updateRejectReason (reasonVo) {
      this.batchUpdateAuditInfo(REVIEW_STATUS_ENUMS.Reject, reasonVo)
    },
    // 批量更新审核信息
    async batchUpdateAuditInfo (auditState, reasonVo) {
      const saveList = []
      this.TableInfo.selection.forEach(item => {
        const index = this.TableInfo.list.findIndex(row => row.skuNo == item.skuNo)
        if (index == -1) return
        const updateRow = {
          ...this.TableInfo.list[index],
          auditState,
          reasonType: reasonVo?.reasonType ?? '',
          reasonNote: reasonVo?.reasonNote ?? ''
        }
        this.$set(this.TableInfo.list, index, updateRow)
        saveList.push(updateRow)
      })
      if (
        reasonVo?.reasonType == REJECT_REASON_ENUMS.Product
        || reasonVo?.reasonType == REJECT_REASON_ENUMS.CategoryAndClassify
      ) return
      await this.submitRecordDetails(saveList)
    },
    // 更新单据明细
    async updateRecordDetails () {
      const data = {
        recordNo: this.$route?.query?.recordNo,
        orderInquiryNo: this.$route?.query?.orderInquiryNo
      }
      const loadingFn = state => { this.pageLoading = state }
      const res = await getTempToPotentialInfoService(data, loadingFn)
      this.TableInfo.setList(res?.retData)
    },
    // 更新替换商品
    updateReplaceProduct (productInfo) {
      this.$set(this.TableInfo.list, this.selectProduct.curIndex, {
        ...this.TableInfo.list[this.selectProduct.curIndex],
        reasonNote: productInfo?.skuNo,
        replaceSkuNo: productInfo?.skuNo,
      })
    },
    // 更新四级类
    updateSelectCategory (categoryInfo) {
      this.$set(this.TableInfo.list, this.selectCategory.curIndex, {
        ...this.TableInfo.list[this.selectCategory.curIndex],
        reasonNote: categoryInfo?.categoryName,
        categoryClassName: categoryInfo?.categoryName,
      })
    },
    // 提交校验
    validateSubmit () {
      const hasNullAuditStatus = this.TableInfo.list.some(item => !item.auditState) // 有审核状态为空的数据
      if (hasNullAuditStatus) return this.$message.warning('审核状态不能为空')
      const hasNullRejectReason = this.TableInfo.list.some(
        item => item.auditState == REVIEW_STATUS_ENUMS.Reject && (!item.reasonType || !item.reasonNote)
      )
      if (hasNullRejectReason) return this.$message.warning('审核驳回的驳回原因和备注不能为空')
    },
    // 提交单据
    async submitRecordDetails (list) {
      const canConfirm = !list
      list = list ?? this.TableInfo.list
      const pickKeys = ['categoryName', 'reasonNote', 'reasonType', 'recordDetailUuid', 'replaceSkuNo']
      const data = list.map(item => ({
        auditState: item.auditState,
        ..._.pick(item, pickKeys)
      }))
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await saveAuditDetailService(data, loadingFn)
      if (isResponseSuccess(res) && canConfirm) {
        this.confirmLeaveCurPage()
      }
    },
    // 校验商品选择
    validateSelectProduct (selectInfo) {
      const curTableRow = this.TableInfo.list[this.selectProduct.curIndex]
      if (selectInfo.unitUuid != curTableRow.unitUuid) {
        this.$message.warning('选择商品计量单位必须一致')
        return false
      }
      if (selectInfo.taxCateNo != curTableRow.taxCateNo) {
        this.$message.warning('选择商品税类必须一致')
        return false
      }
      return true
    },
    // 确认是否离开当前页面
    confirmLeaveCurPage () {
      this.$confirm('提交成功，确认关闭当前页面吗？', '提示', {
        type: 'warning',
      }).then(() => {
        window.close()
      }).catch(() => {})
    },
    // 更新单据明细信息
    async updateRecordFiledsInfo () {
      const data = { recordNo: this.$route?.query?.recordNo }
      const loadingFn = state => { this.pageLoading = state }
      const res = await getByRecordNoService(data, loadingFn)
      this.fieldsData = res?.retData ?? {}
    }
  }
}
</script>
